package com.library.common.config;

import com.library.common.util.RedisUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * redis配置
 *
 * @author: xyh
 * @create: 2023-09-23
 **/
@Configuration
public class RedisConfig {

    /**
     * lettuce实现redis
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> customRedisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 配置连接工厂
        redisTemplate.setConnectionFactory(factory);
        // 设置key序列化方式string，RedisSerializer.string() 等价于 new StringRedisSerializer()
        redisTemplate.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式json，使用GenericJackson2JsonRedisSerializer替换默认序列化，
        // RedisSerializer.json() 等价于 new GenericJackson2JsonRedisSerializer()
        redisTemplate.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化方式
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true);
        // 使配置生效
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 注入封装的RedisTemplate
     *
     * @param redisTemplate
     * @return
     */
    @Bean(name = "redisUtil")
    public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
        RedisUtil redisUtil = new RedisUtil();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }

}
